package test.sum3equals0;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution {
    public static void main(String[] args) {
        int[] nums = {-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6};
        System.out.println(new Solution().threeSum(nums));
    }

    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if (i == 0 || nums[i - 1] != nums[i]) {
                int k = nums.length - 1;
                for (int j = i + 1; j < k; j++) {
                    if (j == i + 1 || nums[j - 1] != nums[j]) {
                        int sum = nums[i] + nums[j] + nums[k];
                        while (sum > 0 && k - 1 > j) {
                            k--;
                            sum = nums[i] + nums[j] + nums[k];
                        }
//                        int sum;
//                        do {
//                            sum = nums[i] + nums[j] + nums[k];
//                            k--;
//                        } while (sum > 0 && k > j);
                        if (sum == 0) {
                            result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                        }
                    }
                }
            }
        }
        return result;
    }
}
//[[-4,-2,6],[-4,0,4],[-4,1,3],[-4,2,2],[-2,-2,4],[-2,0,2]]